const fs = require("fs");
const path = require("path");
const { HarParser } = require("../harAnalysis");

class KnowledgeGenerator {
    constructor(KnowledgePath) {
        this.KnowledgePath = KnowledgePath;
        if (!fs.existsSync(KnowledgePath)) {
            fs.mkdirSync(KnowledgePath, { recursive: true });
        }
        this.knowledge = {};
    }

    generate1(harPath) {
        const harFilePaths = fs.readdirSync(harPath).map(harFileName => path.resolve(harPath, harFileName));
        for (const harFilePath of harFilePaths) {
            const KnowledgeLabel = path.parse(harFilePath).name;
            const harParser = new HarParser(harFilePath);
            const apis = harParser.parse().map(api => api.url.pathname).join("\n");
            this.knowledge[KnowledgeLabel] = apis.toString();
        }
        const knowledgeTxt = Object.keys(this.knowledge).map(label => `${label}\n${this.knowledge[label]}`).join("\n\n");
        const KnowledgeFilePath = path.resolve(this.KnowledgePath, `${Date.now()}.txt`);
        fs.writeFileSync(KnowledgeFilePath, knowledgeTxt);
        return this.knowledge;
    }

    generate(harPath) {
        const harFilePaths = fs.readdirSync(harPath).map(harFileName => path.resolve(harPath, harFileName));
        let knowledgeTxt = "";
        for (const harFilePath of harFilePaths) {
            const KnowledgeLabel = path.parse(harFilePath).name;
            const harParser = new HarParser(harFilePath);
            const apis = harParser.parse().map(api => api.url.pathname);
            apis.forEach((api, index) => {
                if (index % 10 === 0) {
                    knowledgeTxt += `${KnowledgeLabel}\n`
                }
                knowledgeTxt += `${api}\n`;
                if (index % 10 === 9 || index === apis.length-1) {
                    knowledgeTxt += "\n";
                }
            });
        }
        const KnowledgeFilePath = path.resolve(this.KnowledgePath, `${Date.now()}.txt`);
        fs.writeFileSync(KnowledgeFilePath, knowledgeTxt);
        return this.knowledge;
    }
}

module.exports = KnowledgeGenerator;